import re

from Episode import EpisodeInfo

regexp_episode  = re.compile(r'[Ee](?P<episode>\d\d?)')
regexp_season   = re.compile(r'[Ss](?P<season>\d\d?)')

re1 = r'(?P<series>.*)[Ss](?P<season>\d?\d)[Ee](?P<episode>\d\d?)[^\d].*'
re2 = r'(?P<series>.*)[\s\.\_]\[?(?P<season>\d?\d)[Xx](?P<episode>\d\d?)\]?[^\d].*'
re3 = r'(?P<series>.*)[\s\.](?P<season>\d?\d)(?P<episode>\d\d)[^\d].*'
re4 = r'-(?P<series>.*)(?P<season>\d?\d)(?P<episode>\d\d)[^\d].*'

extensions = ['avi','mpg']

class FilenameParser(object):
  def __init__(self):
    self.clear()

  def __call__(self, filepath):
    self.clear()
    return self.parse(filepath)

  def clear(self):
    raise NotImplementedError

  def parse(self,filepath):
    raise NotImplementedError 

class REFilenameParser(FilenameParser):
  def __init__(self, regexp):
    self.regexp = re.compile(regexp)

  def clear(self):
    pass

  def parse(self, filepath):
    match = self.regexp.match(filepath)
    if match:
      match = match.groupdict()
      season   = int( match['season'] )
      episode  = int( match['episode'] )
      series = match['series']
      series = series.rsplit('/',1).pop()
      series = series.replace('.',' ') #Turn periods into spaces
      newseries = [] 
      for c in series:
        if c.isalnum() or c.isspace():
          newseries.append(c)
        else:
          newseries.append(' ')
      series = ''.join(newseries)
      series = series.strip() #Remove space on edges
      series = series.lower() #Convert to lower case
      return EpisodeInfo(series, season, episode)
    else:
      return None

class MultiParser(FilenameParser):
  def __init__(self, parsers):
    self.parsers = parsers

  def clear(self):
    pass

  def parse(self,filepath):
    for parser in self.parsers:
      result = parser.parse(filepath)
      if result:
        return result
    
def parser1():
  return MultiParser([REFilenameParser(exp) for exp in [re1, re2, re3, re4]])
  #return MultiParser([REFilenameParser(exp) for exp in [re1, re2, re3]])

if __name__ == "__main__":
  import sys
  parser = parser1()
  file = open(sys.argv[1])
  serieslist = set()
  faillist=[]
  for entry in file:
    entry = entry.strip()
    if any(entry.endswith(ext) for ext in extensions):
      result = parser(entry)
      if result:
        serieslist.add(result.series_name)
        print entry,result
      else:
        faillist.append(entry)
  print serieslist
  f = open('faillist','w')
  for entry in faillist:
    f.write(entry)
    f.write('\n')
  f.close()
